package com.school.controller.common;

import com.school.config.ProjectConfig;
import com.school.util.Result;
import com.school.util.ResultGenerator;
import com.school.util.TeaShopUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class UploadController {
    @Resource
    private StandardServletMultipartResolver standardServletMultipartResolver= new StandardServletMultipartResolver();


    @PostMapping("/upload/file")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) throws URISyntaxException, IOException {
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        if (bufferedImage == null) {
            return ResultGenerator.genFailResult("文件类型不合法");
        }

        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Random r = new Random();
        String newFileName = sdf.format(new Date()) + r.nextInt(100) + suffixName;

        File fileDirectory = new File(ProjectConfig.getFileUploadPath());

        if (!fileDirectory.exists() && !fileDirectory.mkdirs()) {
            throw new IOException("文件夹创建失败,路径为: " + fileDirectory);
        }

        File destFile = new File(fileDirectory, newFileName);

        try {
            file.transferTo(destFile);
            System.out.println("保存路径：" + destFile.getAbsolutePath());
            System.out.println("是否存在：" + destFile.exists());

            Result resultSuccess = ResultGenerator.genSuccessResult();
            resultSuccess.setData("/upload1/" + newFileName);
            return resultSuccess;
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("文件上传失败");
        }
    }


@PostMapping(value = "/upload/files")
@ResponseBody
public Result upload2(HttpServletRequest request) throws URISyntaxException, IOException {
    ArrayList<MultipartFile> multipartFiles = new ArrayList<>();

    if (standardServletMultipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multipartHttpServletRequest.getFileNames();
        int total = 0;

        while (iter.hasNext()) {
            total++;
            MultipartFile file = multipartHttpServletRequest.getFile(iter.next());
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());

            if (bufferedImage != null) {
                multipartFiles.add(file);
            }
        }

        if (multipartFiles.size() == 0) {
            return ResultGenerator.genFailResult("请选择文件");
        }

        if (multipartFiles.size() > 5) {
            return ResultGenerator.genFailResult("最多上传5个文件");
        }

        List<String> fileNames = new ArrayList<>();

        for (MultipartFile multipartFile : multipartFiles) {
            String fileName = multipartFile.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Random r = new Random();
            String newFileName = sdf.format(new Date()) + r.nextInt(100) + suffixName;
            File fileDirectory = new File(ProjectConfig.getFileUploadPath());
            File destFile = new File(ProjectConfig.getFileUploadPath() + newFileName);

            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdirs()) {
                    throw new IOException("文件夹创建失败，路径为: " + fileDirectory);
                }
            }

            multipartFile.transferTo(destFile);
            fileNames.add(TeaShopUtils.getHost(new URI(ProjectConfig.getServerUrl())) + "/upload1/" + newFileName);
        }

        Result resultSuccess = ResultGenerator.genSuccessResult();
        resultSuccess.setData(fileNames);
        return resultSuccess;
    }

    return ResultGenerator.genFailResult("请求类型错误");
}



}
